#include<stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include "Codec.h"
#include "Packet.h"
#include "PacketController.h"
#define BUF_SIZE 1024
void error_handling(char *message);
int main() {
	int servSock,optVal=1,clntSock,length=0;
	struct sockaddr_in servAddr;
	struct sockaddr_in clntAddr;
	socklen_t clntAdrSize;
	char message[BUF_SIZE];
	char *sendBuffer;
	servSock = socket(PF_INET, SOCK_STREAM, 0);//서버소켓 생성
	if (servSock == -1) {
		error_handling("socket() error");
	}
	memset(&servAddr, 0, sizeof(servAddr));
	servAddr.sin_family = AF_INET;
	servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servAddr.sin_port = htons(atoi("9999"));
	setsockopt(servSock, SOL_SOCKET, SO_REUSEADDR, (void *) &optVal,
			sizeof(int));
	if (bind(servSock, (struct sockaddr*) &servAddr, sizeof(servAddr)) == -1)
		error_handling("bind() error");

	if (listen(servSock, 5) == -1)
		error_handling("listen() error");
	clntAdrSize = sizeof(clntAddr);
	clntSock = accept(servSock,(struct sockaddr *)&clntAddr,&clntAdrSize);
	if(clntSock==-1) error_handling("accept() error");
	memset(message,0,sizeof(message));
	//출력
	read(clntSock,message,BUF_SIZE);
	sendBuffer = PacketHandler(message,&length);
	write(clntSock,sendBuffer,length);
	return 0;
}
void error_handling(char *message) {
	fputs(message, stderr);
	fputc('\n', stderr);
	exit(1);
}
